<template>
  <div class="poster">
    <el-upload
      class="upload"
      action="#"
      :http-request="upload"
      :before-upload="beforeUploadFile"
      :on-success="handleSuccess"
      :show-file-list="false"
    >
      <template slot="trigger">
        <div>点击此处上传文件到OSS</div>
      </template>
    </el-upload>
  </div>
</template>
<script>
import {uploadImg} from '../../../utils/uploadAndDeleteOss'

export default {
  data() {
    return {
      maxSize: 5 * 1024 * 1024, // 单张图片最大质量
      ossConfig: {
        region: "oss-cn-shanghai",
        ossBucket: "kong-zi-liu",
        osskeyId: "LTAI5tQEscGbfY54m3nXAqfj",
        osskeySecret: "Qm5JVOC7dgP05FobWcskxOZ8KN848J",
      }, // oss配置参数
      fileType: "",
      fileList: [],
      fileUrl: "",
    };
  },
  computed: {},
  methods: {
    // 自定义上传图片
    async upload(file) {
      try {
        this.fileType = file.file.type;
        // 上传图片成功返回值
        let imgObj = await uploadImg(this.ossConfig, file.file);
        this.fileUrl = imgObj.url;
      } catch (err) {
        this.$message({
          type: "error",
          message: "上传失败,请稍后再试",
        });
        console.log(err);
      }
    },
    // 文件上传前钩子
    beforeUploadFile(file) {
      return new Promise((resolve, reject) => {
        if (file.size > this.maxSize) {
          this.$message({
            type: "error",
            message: "单张支付凭证不能大于5M",
          });
          return reject(false);
        } else {
          return resolve(true);
        }
      });
    },
    // 文件上传成功钩子
    handleSuccess(res, file, fileList) {
      this.$api
        .addFile({
          url: this.fileUrl,
          name: file.name,
          size: file.size,
          type: this.fileType,
        })
        .then((res) => {
          if (res.success) {
            this.getFileList();
          }
        });
    },
  },
  components: {},
};
</script>
<style lang="scss" sscoped>
.poster {
  width: 100%;
  height: 100%;
  background-color: #eff2f5;
  display: flex;
  flex-direction: column;
  align-items: center;
  .upload {
    width: 95%;
    height: 150px;
    border: 1px dashed #ccc;
    display: flex;
    align-items: center;
    justify-content: center;
    background-color: #fff;
  }
  .upload:hover {
    border-color: #409eff;
  }
}
</style>